package com.ys.peony.car300;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.ccrv.cber.sort.ItemData;
import com.ccrv.cber.sort.CharacterParser;
import com.ccrv.cber.sort.ClearEditText;
import com.ccrv.cber.sort.ItemDataWidthId;
import com.ccrv.cber.sort.LoadingViewUtil;
import com.ccrv.cber.sort.PinyinComparator;
import com.ccrv.cber.sort.SideBar;
import com.ccrv.cber.sort.SortAdapter;
import com.ys.peony.R;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ListSelectActivity extends AppCompatActivity implements View.OnClickListener {

    public final static String ITEM_PARAM = "item";
    public final static String ITEM_PARAM_WIDTH_ID = "item_width_id";
    private View showin;

    private ListView sortListView;
    private SideBar sideBar;
    private TextView dialog;
    private SortAdapter adapter;
    private ClearEditText mClearEditText;
    /**
     * 汉子转为拼音的类
     */
    private CharacterParser characterParser;
    private List<ItemData> SourceDateList;

    /**
     * 根据拼音来排列listview里面的数据类
     */
    private PinyinComparator pinyinComparator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_listselect_activity);
        initBase();
        loadData();
    }

    private void initBase() {
        findViewById(R.id.action_left).setOnClickListener(this);

        //实例化汉子转拼音类
        characterParser = CharacterParser.getInstance();
    }

    private void loadData() {
        Bundle bundle = getIntent().getExtras();
        String items[] = bundle.getStringArray(ITEM_PARAM);
        ItemDataWidthId itemDataWidthId = (ItemDataWidthId) bundle.getSerializable(ITEM_PARAM_WIDTH_ID);
        if(items != null) {
            SourceDateList = filledData(items);
        } else if(itemDataWidthId != null) {
            SourceDateList = filledData(itemDataWidthId);
        }
        //插入数据后再初始化页面
        initViews();
    }

    private void initViews() {
        pinyinComparator = new PinyinComparator();

        sideBar = (SideBar) findViewById(R.id.sidrbar);
        dialog = (TextView) findViewById(R.id.dialog);
        sideBar.setTextView(dialog);

        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }

            }
        });

        sortListView = (ListView) findViewById(R.id.country_lvcountry);
        sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Intent intent = new Intent();
                //返回item数据以及上一页的标记
                intent.putExtra(ITEM_PARAM, (ItemData) adapter.getItem(position));
                setResult(RESULT_OK, intent);
                hideInput();
                finish();
            }
        });

        SourceDateList = filledData(SourceDateList);

        // 根据a-z排序源数据
        Collections.sort(SourceDateList, pinyinComparator);
        adapter = new SortAdapter(this, SourceDateList);
        sortListView.setAdapter(adapter);


        mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);

        //根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }


    /**
     * ΪListView填充数据
     *
     * @param data
     * @return
     */
    private List<ItemData> filledData(String[] data) {
        List<ItemData> mSortList = new ArrayList<ItemData>();
        if (data == null) {
            return null;
        }
        for (int i = 0; i < data.length; i++) {
            ItemData sortModel = new ItemData();
            sortModel.setCar_title(data[i]);
            //汉子转成拼音
            String pinyin = characterParser.getSelling(data[i]);
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否为英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }

    /**
     * ΪListView填充数据
     *
     * @param itemDataWidthId
     * @return
     */
    private List<ItemData> filledData(ItemDataWidthId itemDataWidthId) {
        List<ItemData> mSortList = new ArrayList<ItemData>();
        if (itemDataWidthId == null) {
            return null;
        }
        for (int i = 0; i < itemDataWidthId.getItemDatas().size(); i++) {
            ItemData sortModel = new ItemData();
            sortModel.setCar_title(itemDataWidthId.getItemDatas().get(i).getCar_title());
            //汉子转成拼音
            String pinyin = characterParser.getSelling(itemDataWidthId.getItemDatas().get(i).getCar_title());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否为英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }
            sortModel.setId(itemDataWidthId.getItemDatas().get(i).getId());

            mSortList.add(sortModel);
        }
        return mSortList;

    }

    /**
     * 为ListView填充数据
     *
     * @param data
     * @return
     */
    private List<ItemData> filledData(List<ItemData> data) {
        for (int i = 0; i < data.size(); i++) {
            ItemData sortModel = data.get(i);
            //汉子转成拼音
            String pinyin = characterParser.getSelling(data.get(i).getCar_title());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否为英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }
        }
        return data;
    }

    /**
     * 根据输入框的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<ItemData> filterDateList = new ArrayList<ItemData>();

        if (TextUtils.isEmpty(filterStr)) {
            for (ItemData carType : SourceDateList) {
                if (carType.getCar_title_html() != null) {
                    carType.setCar_title_html(null);
                }
            }
            filterDateList = SourceDateList;
        } else {
            filterDateList.clear();
            for (ItemData sortModel : SourceDateList) {
                String name = sortModel.getCar_title();
                match(filterDateList, sortModel, filterStr);
            }
        }

        if (filterDateList == null || filterDateList.size() == 0) {
            showin = LoadingViewUtil.showinlack(this, R.drawable.icon_theme_search, "没有搜索结果", showin);
        } else {
            LoadingViewUtil.showout(this, showin);
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
    }

    /**
     * 匹配字符串
     *
     * @param sortModel
     * @param filterStr
     */
    private int matchText(ItemData sortModel, String filterStr) {
        int sellingcount = 0;
        String name = sortModel.getCar_title();
        String[] sellingArray = characterParser.getSellingArray(name);
        for (String selling : sellingArray) {
            if ("".equals(filterStr)) {
                return sellingcount;
            }
            if (filterStr.startsWith(selling)) {
                sellingcount++;
                filterStr = filterStr.substring(selling.length(), filterStr.length());
            } else if (selling.startsWith(filterStr)) {
                sellingcount++;
                return sellingcount;
            } else {
                return 0;
            }
        }
        return sellingcount;
    }

    private void match(List<ItemData> filterDateList, ItemData sortModel, String filterStr) {
        boolean isMatch = false;
        String car_title = sortModel.getCar_title();
        int sellingCount = matchText(sortModel, filterStr);
        if (sellingCount != 0) {
            isMatch = true;
            sortModel.setCar_title_html("<font color='#f08519'><b>" + car_title.substring(0, sellingCount) + "</b></font>" + car_title.substring(sellingCount));
        }

        int index = car_title.toLowerCase().indexOf(filterStr.toLowerCase().toString());
        int length = filterStr.length();
        if (index != -1) {
            isMatch = true;
            sortModel.setCar_title_html(car_title.substring(0, index) + "<font color='#f08519'><b>" + filterStr + "</b></font>" + car_title.substring(index + length));
        }

        if (isMatch) {
            filterDateList.add(sortModel);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.action_left:
                finish();
                break;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    private void hideInput() {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        if(imm.isActive()&&getCurrentFocus()!=null){
            if (getCurrentFocus().getWindowToken()!=null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }
}
